<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Symfony\Component\Console\Input\Input;

class ORMController extends Controller
{

    /**
     * 展示
     * @param Request $request
     */
    public function index(Request $request) {
        $where  = $request->input('where');
        $orders = json_decode(json_encode($request->orders), true);
        $model  = self::model();

        if ($where) {
            $where  = json_decode(json_encode($where), true);
            foreach($where as $w) {
                $model = $model->where($w[0], $w[1], $w[2]);
            }
        }
        foreach($orders as $order => $type) {

            $model = $model->orderBy($order, $type);
        }
        $data   = $model->paginate(20);
        return self::success($data);
    }

    public function detail(Request $request) {
        $model = self::model();
        $res = $model->where('id', $request->id)->first();
        return self::success($res);
    }

    /**
     * 创造
     * @param Request $request
     */
    public function create(Request $request) {
        $model = self::model();
        $data = $request->input('data');
        $res = $model->create($data);

        return self::success($res);
    }

    public function import(Request $request) {
        $model = self::model();
        $data = $request->input('data');
        $data = json_decode(json_encode($data), true);
        $model->insert($data);
        return self::success('success');
    }

    public function update(Request $request) {
        $model = self::model();
        $id = $request->input('id');
        $data = $request->input('data');

        $model->where('id', $id)->update($data);

        return self::success('success');
    }

    public function delete(Request $request) {
        $model = self::model();
        $id = $request->input('id');
        $model->where('id', $id)->delete();
        return self::success('success');
    }

    private static function model() {
       $request = request();
       $orm = $request->input('ORM', '');
       if (empty($orm)) {

           throw new \Exception("缺少参数ORM");
       }

       $class = "\\App\\Models\\" . $orm;

       if (!class_exists($class)) {
           throw new \Exception('class:' . $class . '不存在');
       }

       return new $class();
    }
}
